package com.sneakxy.utils;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.lang3.StringUtils;

/**
 * xml转换
 * 
 * @author 飘渺青衣
 * @see
 */
public class JAXBUtils {
	
	public static String toXML(Object obj, String encoding) {
		return toXML(obj, encoding, null);
	}
	
	public static String toXML(Object obj, String encoding, String declaration) {
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);// //编码格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串
            boolean hasDeclaration = !StringUtils.isBlank(declaration);
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, hasDeclaration);// 是否省略xm头声明信息
            StringWriter writer = new StringWriter();
            if(hasDeclaration) {
            	writer.append(declaration).append("\n\r");
            }
            marshaller.marshal(obj, writer);
            return writer.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
	
	public static <T> T fromXML(String xml, Class<T> clazz) {
		try {
			JAXBContext context = JAXBContext.newInstance(clazz);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			JAXBElement<T> jaxbObject = unmarshaller.unmarshal(new StreamSource(new StringReader(xml)), clazz);
			return jaxbObject.getValue();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}
	
}
